package com.design_patterns.proxy.v3;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-30 19:00
 **/

/**
 * 原理是自动生成需要的代码
 */
public class Main {


    /**
     * public final void drawing() {
     * try {
     * super.h.invoke(this, m3, (Object[])null);
     * } catch (RuntimeException | Error var2) {
     * throw var2;
     * } catch (Throwable var3) {
     * throw new UndeclaredThrowableException(var3);
     * }
     * }
     */
    public static void main(String[] args) {
//        这样可以保存生成出来的代码
        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");
        Drawing drawing = (Drawing) Proxy.newProxyInstance(Brush.class.getClassLoader(), new Class[]{Drawing.class}, new BrushLog(new Brush()));
        drawing.drawing();

    }
}


class Brush implements Drawing {

    @Override
    public void drawing() {
        System.err.println("画笔开始画画");
        try {
            Thread.sleep(new Random().nextInt(5000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.err.println("画笔绘画完成");
    }
}

class BrushLog implements InvocationHandler {
    Drawing drawing;

    public BrushLog(Drawing drawing) {
        this.drawing = drawing;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        System.err.println(" before Drawing ");
        drawing.drawing();
        System.err.println(" after Drawing ");
        return null;
    }
}

interface Drawing {
    void drawing();
}